package com.oauth2_security.service.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import com.oauth2_security.entity.UserInfo;
import com.oauth2_security.enums.SystemRest;
import com.oauth2_security.exception.UserNotPermissionException;
import com.oauth2_security.model.RestFulVO;
import com.oauth2_security.service.RequestAuthenticationService;
//import com.ucarbbs.adminweb.dto.MenuDto;
//import com.ucarbbs.adminweb.service.meun.MenuService;

/**
 * 
 * @author dinghao
 *
 */
@Service("requestAuthenticationService")
public class RequestAuthenticationServiceImpl implements RequestAuthenticationService {

    private static Logger authenticationServicelogger = LoggerFactory.getLogger(RequestAuthenticationServiceImpl.class);


    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

//    @Autowired
//    private MenuService menuService;

    /**
     * 路径匹配正则
     * TODO 这里可以定义成为枚举，字典，菜单表新增一个咧，用于匹配使用，现阶段没有必要，因为拥有了菜单等同于拥有了菜单内所有按钮的权限
     */
    private final static String URL_MATCH_STR = "/**";


    @Override
    public boolean isPossessPermission(Authentication authentication, HttpServletRequest request) {
        Object principal =  authentication.getPrincipal();

//        boolean hasPermission = false;
//        if(principal instanceof UserDetails){
//            UserInfo user = (UserInfo)principal;
//            // TODO 1.从readis获取所有菜单权限（读缓存）
//            List<MenuDto> menuList = menuService.getUserMenusCacheByUserId(user.getUserId(),false);
//            // TODO 2.遍历该用户已有的菜单权限
//            for(MenuDto menu : menuList){
//                // TODO 3.通过antPathMatcher进行匹配
//                if(antPathMatcher.match(menu.getMenuUrl() + URL_MATCH_STR,request.getRequestURI())){
//                    hasPermission = true;
//                    break;
//                }
//            }
//            if(!hasPermission){
//                authenticationServicelogger.warn("该用户{}没有{}访问权限", ((UserDetails) principal).getUsername(), request.getRequestURI());
//                throw new UserNotPermissionException(new RestFulVO(SystemRest.USER_NOT_PERMISSION));
//            }
//        }
        return true;
    }
}
